package com.huatai.user.controller;

import cn.hutool.core.net.NetUtil;
import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.client.naming.NacosNamingService;
import com.huatai.common.api.R;

import lombok.extern.slf4j.Slf4j;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PostConstruct;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.*;

/**
 * @program: ht-system
 * @description: ces
 * @author: songxiude
 * @create: 2023-02-16 13:13
 **/
@RestController
@RequestMapping("/test")
@Slf4j
public class TestController {
	@GetMapping("/cs")
	@PreAuthorize("hasAuthority('test_key')")
	public String test() {
		return "ces";
	}

	@GetMapping("/cs2")
	@PreAuthorize("hasAuthority('test_cs2')")
	public String test2() {
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		Object principal = authentication.getPrincipal();
		System.out.println(principal);
		System.out.println("=====");
		System.out.println(authentication.getAuthorities());
		return "ces";
	}

	@GetMapping("/test3")
	public String test3(@RequestParam("name") String name) {
		log.info(name);
		log.warn(name);
		log.error(name);
		return "test" + name;
	}

	/**
	 * 获取nacos属性配置信息
	 */
	@Autowired
	private NacosDiscoveryProperties nacosDiscoveryProperties;

	NacosNamingService nacosNamingService = null;

	@PostConstruct
	public void init() throws NacosException {
		/**
		 * 构建获取nacos服务信息
		 */
		nacosNamingService = new NacosNamingService(nacosDiscoveryProperties.getNacosProperties());
	}

	@GetMapping("/getInstance")
	public Map<String, Object> getInstance() {
		Map<String, Object> resultMap = new HashMap<>();
		try {
			/**
			 * 获取服务名称为testdemo的服务列表信息
			 */
			List<Instance> instances = nacosNamingService.getAllInstances("bi");
			resultMap.put("200", instances);
		} catch (NacosException e) {
			e.printStackTrace();
			resultMap.put("500", e.getMessage());
		}
		return resultMap;
	}


}
